package com.wsc.personalblog.service.impl;

import com.wsc.personalblog.entity.Role;
import com.wsc.personalblog.entity.RoleExample;
import com.wsc.personalblog.entity.UserExample;
import com.wsc.personalblog.mapper.RoleMapper;
import com.wsc.personalblog.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<Role> getRoleInfoByUserId(Integer userId) {
        return roleMapper.getRoleInfoByUserId(userId);
    }

    @Override
    public List<Role> getRoleInfo() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public Integer addRole(Role role) {
        String roleName = role.getName();
        if(roleName == null || roleName.trim().length() == 0)
            throw new RuntimeException("请输入正确的角色信息");
        try {
            roleMapper.insertSelective(role);
            return role.getId();
        }catch (Exception e){
            throw new RuntimeException("该角色已存在");
        }
    }

    @Override
    public void deleteRole(Integer roleId) {
        Integer count = roleMapper.getUserBindInfoByRoleId(roleId);
        if(count != 0) throw new RuntimeException("该角色已被绑定，无法删除");
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void unbindAllUser(Integer roleId) {
        roleMapper.unbindAllUser(roleId);
    }

    @Override
    public List<Role> getRoleInfoByName(String name) {
        if(name == null || name.length() ==0)return roleMapper.selectByExample(null);
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andNameLike("%"+name+"%");
        return roleMapper.selectByExample(roleExample);

    }
}
